﻿using Colorful.Furniture.Wrappers;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Colorful.Furniture.Extensions;
using Colorful.Furniture.ResultManagement;
using Dop.Json;
using Volo.Abp.Authorization;
using Volo.Abp.Validation;
using Volo.Abp;

namespace Colorful.Furniture;

/// <summary>
/// api订单接口错误异常拦截
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class ApiOrderExceptionFilterAttribute : ExceptionFilterAttribute
{
    /// <summary>
    ///  异常
    /// </summary>
    /// <param name="context"></param>
    public override async Task OnExceptionAsync(ExceptionContext context)
    {
        var aaa = context;
       
        var result = new OrderStandardResponseWrapper<object>
        {
            code = context.Exception.Data.ToString(),
            message = context.Exception.Message
        };

        switch (context.Exception)
        {
            //自定义异常
            case UserFriendlyException _:
                
                //将对应的错误码返回
                if (context.Exception is UserFriendlyException userFriendlyException)
                {
                    if (userFriendlyException.Code != default)
                        result.Datas = userFriendlyException.Code;
                }

                break;
                
            default:
                result.message = "接口返回配置错误，请联系管理员";
                result.code = "500";
                break;
        }

        context.HttpContext.Response.ContentType = "application/json;charset=utf-8";
        context.HttpContext.Response.StatusCode = StatusCodes.Status200OK;
       


        //处理HTTP响应内容
        context.HttpContext.Response.Headers.Add("Colorful-Furniture-CustomException", "1");
        //context.HttpContext.Response.StatusCode = result.code.ToInt();
        //context.HttpContext.Response.ContentType = "application/json;charset=utf-8";

        result.code = result.Datas.ToString();
        result.Datas = null;
        await context.HttpContext.Response.WriteAsync(result.ToJson());
        context.ExceptionHandled = true;
    }


}

